from urllib.parse import quote
from flask import make_response, send_file, jsonify


class CreateResponse:
    def __init__(self, ):
        self.msg = 'ok'
        self.code = 0
        self.data = {}

    def __set_response_body(self, data):
        response = make_response(jsonify(data))
        return response

    def __set_response_header(self, response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST,PUT,DELETE'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,token,content-type,range'
        return response

    def construct_response(self, data, msg=None, code=0):
        _msg = msg or self.msg
        _code = code or self.code
        # _data = data or self.data
        _body = {'msg': _msg, 'code': _code, 'data': data}

        _response = self.__set_response_body(_body)
        _response = self.__set_response_header(_response)
        return _response

    def construct_file_response(self, params=dict()):
        filename = params['name']
        start = params['start']
        end = params['end']
        size = params['size']

        if 'piece' in params:
            response = make_response(params['piece'])
            response.headers['Accept-Ranges'] = 'bytes'
            response.headers['Content-Type'] = 'application/octet-stream'
            response.headers['Content-Length'] = '%s' % (size)
            response.headers['Content-Disposition'] = "attachment; filename*=UTF-8''%s" % (
                quote(filename))
            response.headers['Content-Range'] = 'bytes %s-%s/%s' % (
                start, end, size)

        else:
            response = make_response(send_file(
                params['location'], attachment_filename=filename, as_attachment=True, conditional=True))
            response.headers['Content-Range'] = 'bytes %d-%d/%d' % (
                start, end, size)

        return response
